package com.agileboot.domain.airport.report;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.agileboot.common.core.page.PageDTO;
import com.agileboot.domain.airport.danger.db.DangerSourceEntity;
import com.agileboot.domain.airport.danger.db.DangerSourceService;
import com.agileboot.domain.airport.danger.query.DangerSourceQuery;
import com.agileboot.domain.airport.inspection.db.SirInspectionEntity;
import com.agileboot.domain.airport.inspection.db.SirInspectionService;
import com.agileboot.domain.airport.inspectionCheck.db.SirInspectionCheckEntity;
import com.agileboot.domain.airport.inspectionCheck.db.SirInspectionCheckService;
import com.agileboot.domain.airport.reform.ReformMainApplicationService;
import com.agileboot.domain.airport.reform.command.AddReformMainCommand;
import com.agileboot.domain.airport.reform.db.SirReformMainEntity;
import com.agileboot.domain.airport.reform.db.SirReformMainService;
import com.agileboot.domain.airport.reform.db.SirReformMainServiceImpl;
import com.agileboot.domain.common.command.BulkOperationCommand;
import com.agileboot.domain.airport.report.command.AddReportCommand;
import com.agileboot.domain.airport.report.command.UpdateReportCommand;
import com.agileboot.domain.airport.report.db.SirReportEntity;
import com.agileboot.domain.airport.report.db.SirReportService;
import com.agileboot.domain.airport.report.dto.ReportDTO;
import com.agileboot.domain.airport.report.model.ReportModel;
import com.agileboot.domain.airport.report.model.ReportModelFactory;
import com.agileboot.domain.airport.report.query.ReportQuery;
import com.agileboot.domain.system.dept.db.SysDeptEntity;
import com.agileboot.domain.system.dept.db.SysDeptService;
import com.agileboot.domain.system.user.UserApplicationService;
import com.agileboot.domain.system.user.db.SearchUserDO;
import com.agileboot.domain.system.user.db.SysUserService;
import com.agileboot.domain.system.user.dto.UserDTO;
import com.agileboot.domain.system.user.query.SearchUserQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 安全信息应用服务类
 */
@Service
@RequiredArgsConstructor
public class ReportApplicationService {

    private final ReportModelFactory reportModelFactory;

    @Qualifier("sirReportService")
    private final SirReportService reportService;
    private final SirInspectionService sirInspectionService;
    private final SirInspectionCheckService sirInspectionCheckService;
    private final SysUserService sysUserService;
    private final SysDeptService sysDeptService;
    private final ReformMainApplicationService reformMainApplicationService; // 新增注入
    private final SirReformMainService sirReformMainService;
    private final DangerSourceService dangerSourceService;
    private final UserApplicationService userApplicationService; // 新增注入


    public PageDTO<ReportDTO> getReportList(ReportQuery query) {
        // 添加根据inspectionUserName查询用户并设置creator_id的逻辑
        if (StrUtil.isNotEmpty(query.getDiscoverUserName())) {
            SearchUserQuery<SearchUserDO> userQuery = new SearchUserQuery<>();
            userQuery.setUsername(query.getDiscoverUserName());

            // 调用UserApplicationService的getUserList方法查询用户
            PageDTO<UserDTO> userPage = userApplicationService.getUserList(userQuery);
            // 非空校验
            if (userPage != null && CollUtil.isNotEmpty(userPage.getRows())) {
                UserDTO userDTO = userPage.getRows().get(0);
                if (userDTO != null && userDTO.getUserId() != null) {
                    query.setDiscoverer(userDTO.getUserId());
                }
            }else {
                query.setDiscoverer(9999999L);

            }
        }


        Page<SirReportEntity> page = reportService.page(query.toPage(), query.toQueryWrapper());
        List<ReportDTO> records = convertToDTOs(page.getRecords());
        return new PageDTO<>(records, page.getTotal());
    }

    /**
     * 查询所有安全信息，不分页
     */
    public List<ReportDTO> getReportListAll(ReportQuery query) {
        List<SirReportEntity> list = reportService.list(query.toQueryWrapper());
        return convertToDTOs(list);
    }

    public ReportDTO getReportInfo(Long reportId) {
        SirReportEntity entity = reportService.getById(reportId);
        return convertToDTOs(Collections.singletonList(entity)).get(0);
    }

    public void addReport(AddReportCommand command) {
        ReportModel reportModel = reportModelFactory.create();
        reportModel.loadFromAddCommand(command);
        reportModel.insert();
    }

    public void updateReport(UpdateReportCommand command) {
        ReportModel reportModel = reportModelFactory.loadById(command.getReportId());
        reportModel.loadFromUpdateCommand(command);
        reportModel.updateById();
    }

    public void deleteReport(BulkOperationCommand<Long> deleteCommand) {
        // 可扩展校验逻辑，如检查状态是否允许删除等
        reportService.removeBatchByIds(deleteCommand.getIds());
    }

    public void submitReport(UpdateReportCommand command) {

        ReportDTO reportInfo = getReportInfo(command.getReportId());
        AddReformMainCommand reformCommand = new AddReformMainCommand();
        sirReformMainService.deleteByRelatedQuestionId(command.getReportId());
        if(reportInfo.getInspectionCheckId()!=null){
//            这一段是处理检查计划得来的安全信息
            SirInspectionCheckEntity inspectionCheck = sirInspectionCheckService.getById(reportInfo.getInspectionCheckId());
            SirInspectionEntity inspection = sirInspectionService.getById(inspectionCheck.getInspectionId());
            sirReformMainService.deleteByInspectionCheckId(inspectionCheck.getInspectionCheckId());
            // 调用 ReformMainApplicationService.addReform 额外新增一条数据
            reformCommand.setInspectionCheckId(command.getInspectionCheckId());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String codePrefix = inspection.getInspectionCode().substring(0, 4);
            reformCommand.setCode(codePrefix + sdf.format(new Date()));
            reformCommand.setRelatedQuestionId(command.getReportId());
            reformCommand.setQuestionSourceName(mapCodeToNumber(codePrefix));
            reformCommand.setCheckDate(new Date());
            reformCommand.setInspectors(command.getUpdaterBy());
            reformCommand.setQuestionTitle(command.getTitle());
            if (inspectionCheck != null && inspectionCheck.getInspectionQuestion() != null) {
                reformCommand.setReformTitle(new String(inspectionCheck.getInspectionQuestion(), StandardCharsets.UTF_8));
            }
            reformCommand.setDutyDeptId(command.getDutyDeptId());
            reformCommand.setCurDealDeptId(command.getDealDeptId());
            reformCommand.setIssueDeptId(command.getAcceptDeptId());
            reformCommand.setDeleted(false);
            reformCommand.setReformStatus("5");
            reformCommand.setCreatorId(command.getUserId());
            reformCommand.setCreateTime(new Date());
            reformCommand.setReformRequirement(command.getReformRequirement());
            reformCommand.setIssueDeptId(command.getDealDeptId());
            reformCommand.setDutyDeptId(command.getDutyDeptId());
            reformCommand.setRequestFeedbackDate(command.getActionDeadline());
            reformCommand.setCorrectiveDeadline(command.getCorrectiveDeadline());


        } else {
//            这边是处理自愿上报的信息
            // 调用 ReformMainApplicationService.addReform 额外新增一条数据

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            String codePrefix = "ZYSB";
            reformCommand.setCode(codePrefix + sdf.format(new Date()));
            reformCommand.setRelatedQuestionId(command.getReportId());
            reformCommand.setQuestionSourceName(mapCodeToNumber(codePrefix));
            reformCommand.setCheckDate(new Date());
            reformCommand.setInspectors(command.getUpdaterBy());
            reformCommand.setQuestionTitle(command.getTitle());
            reformCommand.setReformTitle(new String(command.getInfoDescribe(), StandardCharsets.UTF_8));
            reformCommand.setDutyDeptId(command.getDutyDeptId());
            reformCommand.setCurDealDeptId(command.getDutyDeptId());
            reformCommand.setIssueDeptId(command.getAcceptDeptId());
            reformCommand.setDeleted(false);
            reformCommand.setReformStatus("5");
            reformCommand.setCreatorId(command.getUserId());
            reformCommand.setCreateTime(new Date());
            reformCommand.setReformRequirement(command.getReformRequirement());
            reformCommand.setIssueDeptId(command.getDealDeptId());
            reformCommand.setDutyDeptId(command.getDutyDeptId());
            reformCommand.setRequestFeedbackDate(command.getActionDeadline());
            reformCommand.setCorrectiveDeadline(command.getCorrectiveDeadline());
            reformCommand.setBasis(command.getBasis());

        }



        reformMainApplicationService.addReform(reformCommand);
        // 新增：查询危险源信息
        DangerSourceQuery query = new DangerSourceQuery();
        query.setRelatedQuestionId(String.valueOf(command.getReportId()));
        List<DangerSourceEntity> all = dangerSourceService.list(query.toQueryWrapper());
        // 根据查询结果更新状态
        String status = all.isEmpty() ? "5" : "4";
        reportService.updateStatusByReportId(command.getReportId(), status);

    }


    private List<ReportDTO> convertToDTOs(List<SirReportEntity> entities) {
        if (entities.isEmpty()) {
            return Collections.emptyList();
        }

        // 收集所有需要查询的 dutyDeptId、discoverer 和 reportId
        Set<Long> deptIds = new HashSet<>();
        Set<Long> userIds = new HashSet<>();
        Set<Long> reportIds = new HashSet<>();

        for (SirReportEntity entity : entities) {
            if (entity.getDutyDeptId() != null) {
                deptIds.add(entity.getDutyDeptId());
            }
            if (entity.getAcceptDeptId() != null) {
                deptIds.add(entity.getAcceptDeptId());
            }
            if (entity.getDiscoverer() != null) {
                userIds.add(entity.getDiscoverer());
            }
            if (entity.getReportId() != null) {
                reportIds.add(entity.getReportId());
            }
        }

        // 批量查询部门信息
        Map<Long, SysDeptEntity> deptMap = new HashMap<>();
        if (!deptIds.isEmpty()) {
            deptMap = sysDeptService.getByDeptIds(new ArrayList<>(deptIds)).stream()
                    .collect(Collectors.toMap(com.agileboot.domain.system.dept.db.SysDeptEntity::getDeptId, e -> e));
        }

        // 批量查询用户信息
        Map<Long, com.agileboot.domain.system.user.db.SysUserEntity> userMap = new HashMap<>();
        if (!userIds.isEmpty()) {
            userMap = sysUserService.getByUserIds(new ArrayList<>(userIds)).stream()
                    .collect(Collectors.toMap(com.agileboot.domain.system.user.db.SysUserEntity::getUserId, e -> e));
        }

        // 批量查询整改记录
        Map<Long, String> reformCodeMap = new HashMap<>();
        if (!reportIds.isEmpty()) {
            List<SirReformMainEntity> reformEntities = sirReformMainService.getByRelatedQuestionIds(new ArrayList<>(reportIds));
            reformCodeMap = reformEntities.stream()
                    .collect(Collectors.toMap(
                            SirReformMainEntity::getRelatedQuestionId,
                            SirReformMainEntity::getCode,
                            (existing, replacement) -> existing // 处理重复的关联关系
                    ));
        }

        // 转换为 DTO 并赋值
        List<ReportDTO> dtos = new ArrayList<>();
        for (SirReportEntity entity : entities) {
            ReportDTO dto = new ReportDTO(entity);

            // 设置部门名称
            if (entity.getDutyDeptId() != null) {
                com.agileboot.domain.system.dept.db.SysDeptEntity dept = deptMap.get(entity.getDutyDeptId());
                if (dept != null) {
                    dto.setDeptName(dept.getDeptName());
                }
            }

            // 设置处理单位名称
            if (entity.getAcceptDeptId() != null) {
                com.agileboot.domain.system.dept.db.SysDeptEntity dept = deptMap.get(entity.getAcceptDeptId());
                if (dept != null) {
                    dto.setDealDeptName(dept.getDeptName());
                }
            }

            // 设置用户名称
            if (entity.getDiscoverer() != null) {
                com.agileboot.domain.system.user.db.SysUserEntity user = userMap.get(entity.getDiscoverer());
                if (user != null) {
                    dto.setDiscoverUserName(user.getUsername());
                }
            }

            // 设置关联的整改通知书编号
            dto.setRelatedReformCode(reformCodeMap.get(entity.getReportId()));

            dtos.add(dto);
        }

        return dtos;
    }

    // 辅助方法：将检查代码前缀映射为数字
    private String mapCodeToNumber(String codePrefix) {
        Map<String, String> codeMap = new HashMap<>();
        codeMap.put("FDZC", "1");
        codeMap.put("ZXJC", "2");
        codeMap.put("AQZL", "3");
        codeMap.put("ZYSB", "4");

        return codeMap.getOrDefault(codePrefix, "未知类型");

    }

}
